package tools

import (
	"errors"
	"github.com/golang-jwt/jwt/v5"
	"liuche17.cn/go-blog/server/global"
	"liuche17.cn/go-blog/server/model/system"
	"strconv"
	"strings"
	"time"
)

type JWT struct {
	SigningKey []byte
}

var (
	TokenInvalid = errors.New("token validate error")
)

// GenerateToken 生成token
func GenerateToken(user system.JwtUser) (string, error) {
	// 唯一标识
	signingKey := []byte(global.GB_CONFIG.JWT.SigningKey)
	// 构造 claims
	exp, _ := strconv.ParseInt(global.GB_CONFIG.JWT.ExpiresTime, 10, 64)
	ep := time.Duration(exp) * time.Minute // 过期时间
	claims := system.CustomClaims{
		JwtUser: system.JwtUser{
			Id:   user.Id,
			Role: user.Role,
		},
		RegisteredClaims: jwt.RegisteredClaims{
			Audience:  jwt.ClaimStrings{"GB"},
			Issuer:    global.GB_CONFIG.JWT.Issuer,
			Subject:   strconv.FormatInt(int64(user.Id), 10),
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(ep)),
		},
	}
	// 生成 token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(signingKey)
}

func ParseToken(jwtStr string) (*system.CustomClaims, error) {
	key := []byte(global.GB_CONFIG.JWT.SigningKey)
	// 解析token
	token, err := jwt.ParseWithClaims(jwtStr, &system.CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return key, nil
	})
	if err != nil {
		return nil, TokenInvalid
	}
	if token != nil {
		if claims, ok := token.Claims.(*system.CustomClaims); ok && token.Valid {
			return claims, nil
		}
	}
	return nil, TokenInvalid
}

// GetLoginUserInfo 根据token得到登录用户信息
func GetLoginUserInfo(token string) (*system.JwtUser, error) {
	claims, err := ParseToken(token)
	if err != nil {
		return nil, err
	}

	return &claims.JwtUser, nil
}

// ParseDuration 解析时间
func ParseDuration(d string) (time.Duration, error) {
	d = strings.TrimSpace(d)
	dr, err := time.ParseDuration(d)
	if err == nil {
		return dr, nil
	}
	if strings.Contains(d, "d") {
		index := strings.Index(d, "d")

		hour, _ := strconv.Atoi(d[:index])
		dr = time.Hour * 24 * time.Duration(hour)
		ndr, err := time.ParseDuration(d[index+1:])
		if err != nil {
			return dr, nil
		}
		return dr + ndr, nil
	}

	dv, err := strconv.ParseInt(d, 10, 64)
	return time.Duration(dv), err
}
